import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';

import ContractLayout from '@/component/contract/Layout';
import MTable from '@/component/common/MTable';
import MModal from '@/component/common/MModal';
import HouseInfoModal from '@/component/house/HouseInfoModal';
import helper from '@/tool/helper';

import { Pagination, Form, Input, Select, DatePicker } from 'antd';
import BtnStyle from '@/common/btns.scss';

const FormItem = Form.Item;
const Option = Select.Option;
const mConfirm = MModal.confirm;
const { RangePicker } = DatePicker;

import contractStyle from './contract.scss';

import FilterListPage from '@/component/common/FilterListPage';
import ApiHelper from '@/store/ApiHelper';
import StoreListMini from '@/store/StoreListMini';
import BrokerListMini from '@/store/BrokerListMini';

import { contract_list, terminate_contract, stage_settlement, contract_overdue_notify,
    contract_pay_info } from '@/constants/ApiTypes';
import adminType from '@/tool/adminType';

// const testData = [
//     { a: '12345678', b: '合租', c: '吴超', d: '乔司', e: '1200元', f: '哼哒哥', g: '12345678901', h: '2017-10-08至2018-10-07', i: '月付', j: '1200元' },
//     { a: '12345678', b: '合租', c: '吴超', d: '乔司', e: '1200元', f: '哼哒哥', g: '12345678901', h: '2017-10-08至2018-10-07', i: '月付', j: '1200元' }
// ];

//房租提醒确认
const notifyOverdueConfirm = async (contract_no, refresh = false) => {
    mConfirm({
        title: '确定要房租提醒吗',
        titleStyle: { fontSize: 16 },
        width: 300,
        height: 177,
        content: '',
        okText: '是',
        cancelText: '否',
        okClassName: 'primary-btn-ok',
        cancelClassName: 'primary-btn-cancel',
        showTopClose: false,
        onOk: async () => {
            const data = { contract_no };
            const result = await ApiHelper.requestPost(contract_overdue_notify, data);
            if (result.status) {
                MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                if (refresh) refresh();
                //关闭对话框，刷新数据
            } else {
                MModal.success({ title: '操作失败', content: result.info });
            }
        },
        onCancel() { }
    });
};

class PayInfoListModal extends FilterListPage {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        contract_no: PropTypes.string.isRequired,
        contract_overdue_notify: PropTypes.bool.isRequired
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.listApiType = contract_pay_info;
            this._setState({ result_info: [] });
            this.getDataListWithFilter({ contract_no: nextProps.contract_no });
        }
    }
    //房租提醒确认
    notifyOverdueConfirm = async contract_no => {
        await notifyOverdueConfirm(contract_no, () => this.props.onClose(true));
    };
    render() {
        const { visible, onClose, contract_overdue_notify } = this.props;
        const columns = [
            { title: '合同编号', dataIndex: 'contract_no', align: 'middle' },
            { title: '交租日前', dataIndex: 'item_date', align: 'middle' },
            { title: '房租金额', dataIndex: 'item_price', align: 'middle', render: (text, record, dataIndex) => isNaN(text) ? text : text / 100 + '元' },
            { title: '是否支付', dataIndex: 'pay_status', align: 'middle', render: (text, record, dataIndex) => text == 0 ? '未支付' : '已支付' },
            { title: '是否逾期', dataIndex: 'overdue', align: 'middle', render: (text, record, dataIndex) => text == 0 ? '未逾期' : '逾期' },
            { title: '操作', dataIndex: 'create_time', align: 'middle', render: (text, record, dataIndex) => contract_overdue_notify ?
                <a href="javascript:void(0);" className={BtnStyle['btn-default']} onClick={() => this.notifyOverdueConfirm(this.props.contract_no)}>房租提醒</a> :
                <a href="javascript:void(0);" className={`${BtnStyle['btn-default']} ${BtnStyle['disabled']}`}>房租提醒</a> }
        ];
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={750} height={helper.fixHeight(600)}>
                <div className={contractStyle['table-modal']}>
                    <h1 className={contractStyle['title']}>支付情况</h1>
                    <MTable columns={columns}
                        scroll={{ y: helper.fixHeight(600) - 150 }}
                        dataSource={Array.isArray(this.state.result_info) ? this.state.result_info : []}
                        spinning={this.state.spinning}/>
                </div>
            </MModal>
        );
    }
}

@observer class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        onSubmit: PropTypes.func
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.props.onSubmit) {
                    for (let key in values) {
                        if (values[key] === '') delete values[key];
                        //处理date_range
                        if (key == 'date_range') {
                            if (Array.isArray(values[key]) && values[key].length > 0) {
                                values.start_time = values[key][0].unix();
                                values.end_time =  values[key][1].unix();
                            }
                            delete values[key];
                        }
                    }
                    this.props.onSubmit(values);
                }
            }
        });
    };
    selectStore = value => {
        this.props.form.setFieldsValue({ broker_name: '' });
        if (value == '') {
            return BrokerListMini.info.clear();
        }
        BrokerListMini.getInfo(value);
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const storeListMini = StoreListMini.info;
        const brokerListMini = BrokerListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.realname}`}>{val.realname}</Option>;
        });
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                {adminType() == 1 &&
                <FormItem label="门店">
                    {getFieldDecorator('store_id', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore}>
                            <Option key="default" value="">不限</Option>
                            {storeOptionList}
                        </Select>
                    )}
                </FormItem>}
                <FormItem label="经纪人">
                    {getFieldDecorator('broker_name', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择经纪人" style={{ width: 150 }}>
                            <Option key="default" value="">不限</Option>
                            {brokerOptionList}
                        </Select>
                    )}
                </FormItem>
                <FormItem label="合同编号">
                    {getFieldDecorator('contract_no', {
                        initialValue: ''
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem label="合同状态">
                    {getFieldDecorator('contract_status', {
                        initialValue: "0"
                    })(
                        <Select style={{ width: 150 }}>
                            <Option value="0">全部</Option>
                            <Option value="1">分期</Option>
                            <Option value="2">逾期</Option>
                            <Option value="3">欠费</Option>
                            <Option value="4">一个月到期</Option>
                        </Select>
                    )}
                </FormItem>
                <FormItem label="创建时间">
                    {getFieldDecorator('date_range', {
                        initialValue: ''
                    })(
                        <RangePicker/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={contractStyle['submit-btn']} type="submit">搜索</button>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

@observer class ContractList extends FilterListPage {
    constructor(props) {
        super(props);
        this.defaultQuery = {
            contract_type: 0 //合同列表
        };
        this.listApiType = contract_list;
        const state = {
            payInfoListModalVisible: false,
            payInfoListModalProps: {
                contract_no: '',
                contract_overdue_notify: false
            },
            houseInfoModalVisible: false,
            houseInfoModalProps: {
                itemInfo: {}
            }
        };
        this._setDefaultState(state);
    }
    async pageDidMount() {
        const result = await StoreListMini.getInfo();
        if (!result) return;
        this._setState({ loading: false });
    }
    showPayInfoListModal = (contract_no, contract_overdue_notify) => {
        this._setState({
            payInfoListModalVisible: true,
            payInfoListModalProps: {
                contract_no,
                contract_overdue_notify
            }
        });
    };
    closePayInfoListModal = (refresh = false) => {
        if (refresh == true) this.refresh();
        this._setState({ payInfoListModalVisible: false });
    };
    terminateContract = async contract_no => {
        const data = { contract_no };
        const result = await ApiHelper.requestPost(terminate_contract, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
            //刷新列表
            this.refresh();
            return result.info;
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    //支付分期合同剩余本金
    payStageContract = (pay_amount, contract_no) => {
        //pay_amount 待还本金
        if (pay_amount === false) return;
        mConfirm({
            title: '合同已终止',
            width: 420,
            height: 200,
            content: hide => {
                return (
                    <div>待还本金 <span style={{ marginLeft: 10, color: 'red' }}>{pay_amount / 100}元</span>
                        <a className="primary-btn-ok"
                            style={{ marginLeft: 30 }}
                            href="javascript:void(0);" onClick={() => this.payStageAmountConfirm(hide, contract_no)}>去支付</a>
                    </div>
                );
            },
            contentStyle: { width: 300, height: 100 },
            showBtn: false,
            showTopClose: true,
            onOk() {},
            onCancel() { }
        });
    };
    //支付分期合同剩余本金确认
    payStageAmountConfirm = async (hide, contract_no) => {
        mConfirm({
            title: '确定要支付吗',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { contract_no };
                const result = await ApiHelper.requestPost(stage_settlement, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    //关闭对话框，刷新数据
                    hide();
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() { }
        });
    };
    //终止合同确认
    terminateContractConfirm = contract_info => {
        const { contract_type } = contract_info;
        if (contract_type == '普通合同') {
            mConfirm({
                title: '终止合同',
                content: '合同终止后，双方合同即终止，租客将不能再支付房租。',
                contentStyle: { width: 320, height: 160 },
                okText: '终止',
                showTopClose: false,
                onOk: () => this.terminateContract(contract_info.contract_no),
                onCancel() { }
            });
        } else {
            mConfirm({
                title: '终止分期合同',
                content: () => {
                    if (contract_info.stage_will_pay) {
                        return <span dangerouslySetInnerHTML={{ __html: '分期合同终止后，双方合同即终止，租客将不能再支付房租，<br/>剩余本金（￥' + contract_info.stage_will_pay / 100  + '元）将由您立即支付。' }} />
                    } else {
                        return <span dangerouslySetInnerHTML={{ __html: '分期合同终止后，双方合同即终止，租客将不能再支付房租。' }} />
                    }
                },
                contentStyle: { width: 320, height: 160 },
                okText: '终止',
                showTopClose: false,
                onOk: async () => {
                    const info = await this.terminateContract(contract_info.contract_no);
                    this.payStageContract(info.pay_amount);
                },
                onCancel() { }
            });
        }

    };
    //房租提醒确认
    notifyOverdueConfirm = async contract_no => {
        await notifyOverdueConfirm(contract_no, this.refresh);
    };
    closeHouseInfoModal = (refresh = false) => {
        if (refresh) this.searchHouseList();
        this.setState({ houseInfoModalVisible: false });
    };
    showHouseInfoModal = itemInfo => {
        this.setState({
            houseInfoModalVisible: true,
            houseInfoModalProps: {
                itemInfo
            }
        });
    };
    render() {
        const contract_status =  (text, record, dataIndex) => {
            //逾期合同显示终止合同按钮，分期且终止的合同显示去支付
            if (record.overdue_day > 0 && record.contract_status == 0) {
                return <a href="javascript:void(0);" className={BtnStyle['btn-danger']} onClick={() => this.terminateContractConfirm(record)}>终止合同</a>
            }
            if (record.contract_status == 1) {
                if (record.contract_type == '分期合同' && record.stage_will_pay) {
                    return <a href="javascript:void(0);" className={BtnStyle['btn-primary']} onClick={() => this.payStageContract(record.stage_will_pay, record.contract_no)}>去支付</a>
                }
                return '已终止';
            }
            return '正常';
        };
        const contract_oper = (text, record, dataIndex) => {
            const hide_cui = record.overdue_day == 0 ? { visibility: 'hidden' } : null;
            const itemInfo = {
                house_no: record.house_no,
                address_detail: record.house_address_detail,
                community: record.community,
                broker_id: record.broker_id
            };
            const can_notify = record.overdue_day && record.contract_overdue_notify;
            return (
                <div>
                    <a href="javascript:void(0);" className={BtnStyle['btn-default']} onClick={() => this.showHouseInfoModal(itemInfo)}>详情</a>
                    <a href="javascript:void(0);" className={BtnStyle['btn-default']} onClick={() => this.showPayInfoListModal(record.contract_no, record.contract_overdue_notify)}>支付情况</a>
                    <a href="javascript:void(0);" className={can_notify ? BtnStyle['btn-warn'] : `${BtnStyle['btn-warn']} ${BtnStyle['disabled']}`}
                        style={hide_cui} onClick={can_notify ? () => this.notifyOverdueConfirm(record.contract_no) : () => {}}>催</a>
                </div>
            );
        };
        const columns = [
            { title: '合同编号', dataIndex: 'contract_no', align: 'middle' },
            { title: '租赁方式', dataIndex: 'rent_type', align: 'middle' },
            { title: '经纪人', dataIndex: 'broker_name', align: 'middle' },
            { title: '物业地址', dataIndex: 'community', align: 'middle' },
            { title: '租金', dataIndex: 'rent_info', align: 'middle', render: (text, record, dataIndex) => isNaN(text) ? text : text / 100 + '元' },
            { title: '客户', dataIndex: 'renter_name', align: 'middle' },
            { title: '联系电话', dataIndex: 'renter_mobile', align: 'middle' },
            { title: '租期', dataIndex: 'rent_time', align: 'middle' },
            { title: '付款', dataIndex: 'pay_type', align: 'middle' },
            { title: '押金', dataIndex: 'deposit', align: 'middle', render: (text, record, dataIndex) => isNaN(text) ? text : text / 100 + '元' },
            { title: '合同状态', dataIndex: 'k', align: 'middle', render: contract_status },
            { title: '操作', dataIndex: 'l', align: 'middle', render: contract_oper }
        ];
        const { dataList, result_info, spinning, payInfoListModalVisible, payInfoListModalProps,
            houseInfoModalVisible, houseInfoModalProps } = this.state;
        return (
            <ContractLayout loading={this.state.loading}>
                <div className={contractStyle['top-filter']}>
                    <FilterWrapped onSubmit={this.getDataListWithFilter} />
                </div>
                <div className={contractStyle['contract-sum']}>
                    <span>应收房租：{result_info.sum_head ? result_info.sum_head.rent_will_pay / 100 : 0}元</span>
                    <span>合同到期：{result_info.end_count ? result_info.end_count : 0}套</span>
                </div>
                <MTable columns={columns} dataSource={dataList} spinning={spinning}/>
                <div className={contractStyle['contract-sum']}>
                    <span>总待收房租：{result_info.sum_head ? result_info.sum_head.rent_will_get / 100 : 0}元</span>
                    <span>逾期：{result_info.sum_head ? result_info.sum_head.house_overdue : 0}套</span>
                    <span>欠费：{result_info.sum_head ? result_info.sum_head.house_arrear : 0}套</span>
                </div>
                <PayInfoListModal onClose={this.closePayInfoListModal} visible={payInfoListModalVisible} {...payInfoListModalProps} />
                <HouseInfoModal visible={houseInfoModalVisible} onClose={this.closeHouseInfoModal} {...houseInfoModalProps} />
                <div className="pagination">
                    {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                </div>
            </ContractLayout>
        );
    }
}

export default ContractList;